import { useRequestHandle } from '@/utils/utils';
import { Steps, Card, Badge,Button } from 'antd';
import { useMatch,history } from 'umi';
import { getById, getPublishFlowById, getHealthy, savePublishFlowNode, surePublish, commandRunScript } from './service';
import { useEffect, useState } from 'react';
import { useUpdateEffect } from '@umijs/hooks';
import { Space } from 'antd';
import Backup from "./components/Backup";
import MakePack from "./components/MakePack";
import SurePublish from "./components/SurePublish";
import RunScript from "./components/RunScript";
import { message } from 'antd';
import { RollbackOutlined } from '@ant-design/icons';



export default () => {
  const match = useMatch('/system/developer/applications/publishflow/:id');
  const id = match?.params.id;
  const [serverConfig, setServerConfig] = useState({});
  const [publishFlow, setPublishFlow] = useState({});
  const [healthy, setHealthy] = useState(false);
  const [current, setCurrent] = useState(0);
  const [scriptResult, setScriptResult] = useState([]);
  const getHealthyRequest = useRequestHandle(getHealthy, () => {
    setHealthy(true);
  });
  const savePublishFlowNodeRequest = useRequestHandle(savePublishFlowNode, () => {
    setCurrent(current + 1);
  });
  const surePublishRequest = useRequestHandle(surePublish, () => {
    setCurrent(current + 1);
  });
  const runScriptRequest = useRequestHandle(commandRunScript, (data) => {
    message.success("执行成功");
    setScriptResult(data);
  });
  const getHealthyCheck = () => {


    if (getHealthyRequest.loading) {
      return <Badge status="processing" text="检查中" />
    }

    if (healthy) {
      return <Badge status="success" text="服务器在线" />
    }

    return <Badge status="error" text="服务器离线" />




  }
  useEffect(() => {
    async function init() {

      const r1 = await getPublishFlowById({ id })
      setPublishFlow(r1.data);
      const response = await getById({ id: r1.data.agentServerConfigId });
      if (response && response.success) {
        setServerConfig(response.data);
      }
    }
    init();
  }, [id])
  useUpdateEffect(() => {
    if (serverConfig.id) {
      getHealthyRequest.run({ id: serverConfig.agentServerId });
    }
  }, [serverConfig]);
  useUpdateEffect(() => {
    if (publishFlow.id) {
      setCurrent(publishFlow.nodes.length);
    }
  }, [publishFlow])
  return (
    <>
      <Card title={<Space >
        <Button type='link' size='small'
          onClick={() => {
            history.push("/system/developer/applications/publishflow");
          }}
          icon={<RollbackOutlined />}>返回</Button>
        {serverConfig.agentServer?.serverName}
        {serverConfig.serverName}
        {getHealthyCheck()}
      </Space>}>
        <div>请确认发布内容是否正确</div>
        <Steps
          style={{ width: "100%" }}
          current={current}

          items={[
            {
              title: '备份',
            },
            {
              title: '上传',
            },
            {
              title: '发布',
            },
            {
              title: '脚本',
            },
          ]}
        />
        <div style={{ marginTop: "10px" }}>
          {current === 0 ? <Backup
            loading={savePublishFlowNodeRequest.loading}
            onBackup={(path) => {
              savePublishFlowNodeRequest.run({ result: path, publishFlowId: publishFlow.id, nodeType: 1 });
            }} record={serverConfig} /> : null}

          {current === 1 ? <MakePack
            id={id}
            loading={savePublishFlowNodeRequest.loading}
            onSuccess={(path) => {
              savePublishFlowNodeRequest.run({ result: path, publishFlowId: publishFlow.id, nodeType: 2 });
            }} record={serverConfig} /> : null}
          {current === 2 ? <SurePublish
            id={id}
            loading={surePublishRequest.loading}
            onSuccess={(isIis) => {
              surePublishRequest.run({ id: publishFlow.id, isAutoStopReStart:isIis?isIis:false});
            }} record={serverConfig} /> : null}


          {current === 3 ? <RunScript
            id={id}
            loading={surePublishRequest.loading}
            onRun={(d) => {
              runScriptRequest.run({ id: publishFlow.id, command: d });
            }} record={serverConfig}

            result={scriptResult}
          /> : null}
        </div>
      </Card>
    </>
  );
};
